const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-generic-session')
const redisStore = require('koa-redis')

const { REDIS_CONF } = require('./conf/db')
const { isProd } = require('./utils/env')
const { CRYPTO_SCERET_KEY } = require('./conf/secretKeys')

// 路由
const index = require('./routes/index')
// const users = require('./routes/users')
const userViewRouter = require('./routes/view/user')
const userAPIRouter = require('./routes/api/user')
const errorViewRouter = require('./routes/view/error')

// error handler  错误配置项 当遇到错误时跳转到error路由上
let onerrorConf = {}

if (isProd) {
    onerrorConf = {
    redirect: '/error'
  }
}// 如果是生产环境跳转到错误页，本地环境则不跳转


onerror(app, onerrorConf)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))


// session 配置
app.keys = [CRYPTO_SCERET_KEY];
app.use(session({
  key: 'tieba.sid',   // cookie name 默认是 'koa.sid'
  prefix: 'tieba:sess:', // redis key 的前缀，默认是 `koa:sess:`
  cookie: {
    path: '/',
    httpOnly: true,
    maxAge: 24 * 60 * 60 * 1000
  },//只能通过server端修改cookie 有过期时间(这设的是一天)
 // ttl: 24 * 60 * 60 * 1000,  // redis 过期时间不写默认与cookie相同
  store: redisStore({
    all: `${REDIS_CONF.host}:${REDIS_CONF.port}`
  })
}))

/*
// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
*/

// 引入完后的注册路由 routes
app.use(index.routes(), index.allowedMethods())   
// app.use(users.routes(), users.allowedMethods())
app.use(userAPIRouter.routes(), userAPIRouter.allowedMethods())
app.use(userViewRouter.routes(), userViewRouter.allowedMethods())
app.use(errorViewRouter.routes(), index.allowedMethods())  // 注意：404路由要注册到最下面


// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
